<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>DEMO3 - 刮刮卡</title>
    <script src="../avg.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"
    />
    <style>
        * {
            border: 0;
            margin: 0;
            padding: 0;
        }
    </style>
</head>

<body>
    <script>

        avg.creaveWindow({
            width: 480,
            height: 320,
        });

        //移动端兼容来自 https://www.jianshu.com/p/3fef68afd139
        //简书用户 小厨笔记
        //pc，移动事件兼容写法
        var hastouch = "ontouchstart" in window,
            tapstart = hastouch ? "touchstart" : "mousedown",
            tapmove = hastouch ? "touchmove" : "mousemove",
            tapend = hastouch ? "touchend" : "mouseup";

        var canvasMask = document.createElement("canvas");
        var context2d = canvasMask.getContext("2d");

        canvasMask.width = 480;
        canvasMask.height = 320;

        context2d.lineCap = "round";
        context2d.lineJoin = "round";

        var pointerFromX;
        var pointerFromY;

        var pointerToX;
        var pointerToY;

        var lineWidthDef = 48;

        function drawLine({ fromX = pointerFromX, fromY = pointerFromY } = {}, { toX = pointerToX, toY = pointerToY } = {}, lineWidth = lineWidthDef) {
            context2d.save();
            context2d.moveTo(fromX, fromY);
            context2d.lineTo(toX, toY);
            context2d.lineWidth = lineWidth;
            context2d.stroke();
            context2d.restore();
        }

        /**
         * @type {HTMLCanvasElement}
         */
        var canvasMain = avg.getDOM();

        var tapFlag = false;

        canvasMain.addEventListener(tapstart, e => {
            tapFlag = true;
            pointerToX = avg.mouse.x;
            pointerToY = avg.mouse.y;
        });

        canvasMain.addEventListener(tapmove, e => {
            if (tapFlag) {
                pointerFromX = pointerToX;
                pointerFromY = pointerToY;
                pointerToX = avg.mouse.x;
                pointerToY = avg.mouse.y;
                drawLine();
            }
        });

        document.documentElement.addEventListener(tapend, e => {
            tapFlag = false;
        });

        avg.loadImage({
            layer: 18,
            src: "image/background/logo.png",
            x: 0,
            y: 0,
            width: 480,
            height: 320
        });
        avg.loadImage({
            layer: 19,
            img: canvasMask,
            x: 0,
            y: 0,
            width: 480,
            height: 320
        });
        avg.loadImage({
            layer: 20,
            src: "image/gifExample.png",
            x: 0,
            y: 0,
            width: 480,
            height: 320,
            mask: "mask"
        });

    </script>
</body>